//
//  appendPhotosVC.swift
//  weibo1
//
//  Created by 李进 on 15/10/27.
//  Copyright © 2015年 李进. All rights reserved.
//

import UIKit

class appendPhotosVC: UICollectionViewController {
    
    var selectionIndex:Int = 0
    /// 数据数组
     var arrayList = [UIImage]()
    
    /// 便利构造函数
    ///
    /// - returns: 返回控制器
    init(){
        super.init(collectionViewLayout: appendPhotosCVFlowLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(appendPhotosCollectionViewCell.self, forCellWithReuseIdentifier: appendPhotosCollectionViewCellId)
        
        collectionView?.backgroundColor = UIColor.lightGrayColor()

    }

    /// 数据源方法
    ///
    /// - parameter collectionView: collectionView description
    /// - parameter section:        section description
    ///
    /// - returns: return value description
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return arrayList.count + (arrayList.count == 8 ? 0 : 1)
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(appendPhotosCollectionViewCellId, forIndexPath: indexPath) as! appendPhotosCollectionViewCell
        
        cell.appimageDelegate = self
        
        if indexPath.item == arrayList.count  {
            cell.image = nil
        }else{
            
            cell.image = arrayList[indexPath.item]
        }
        cell.backgroundColor = UIColor.grayColor()
        
        return cell
    }
    
    /// MARK: -设置流水布局
    class appendPhotosCVFlowLayout: UICollectionViewFlowLayout{
        
        let cellMargin: CGFloat = UIScreen.mainScreen().scale * 4
        
        override func prepareLayout() {
            super.prepareLayout()
            let count: CGFloat = 4
            //let margin = UIScreen.mainScreen().scale * 4
            let w = (collectionView!.bounds.width - (count + 1) * cellMargin) / count
            minimumLineSpacing = cellMargin
            minimumInteritemSpacing = cellMargin
            scrollDirection = .Vertical
            itemSize = CGSizeMake(w, w)
            sectionInset = UIEdgeInsetsMake(cellMargin, cellMargin, 0, cellMargin)
        }
        
    }

}

// MARK: - appendPhotosCollectionViewCellDelegate实现代理方法
extension appendPhotosVC:appendPhotosCollectionViewCellDelegate{
    
    
/// 判断是否支持图库
 private  func createPicker(){
        //判断是否支持图库
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            print("无法访问图库")
            return
        }
        
        //创建图像显示器
        let picker = UIImagePickerController()
        
        //设置代理
        picker.delegate = self
        //显示图片选择器
        presentViewController(picker, animated: true, completion: nil)
    }
    
    //添加图片
    @objc private func appendPhotosCollectionViewCellfunc(){
       selectionIndex = arrayList.count
        createPicker()
        
    }
    //更换图片
    @objc private func imgeviewReoptionImage(cell:appendPhotosCollectionViewCell) {
        
        let indexpath = collectionView?.indexPathForCell(cell)
        //print(indexpath)
        selectionIndex = indexpath!.item
        createPicker()
    }
    //删除图片
    @objc private func removeButImage(cell:appendPhotosCollectionViewCell){
        // print("删除图片")
        let indexpath = collectionView?.indexPathForCell(cell)
       // print(indexpath)
        
        arrayList.removeAtIndex((indexpath?.item)!)
        collectionView?.reloadData()
    }
}


//MARK: - 声明代理方法
@objc
private protocol appendPhotosCollectionViewCellDelegate: NSObjectProtocol {
    //添加图片
    func appendPhotosCollectionViewCellfunc()
    //更换图片
    func imgeviewReoptionImage(cell:appendPhotosCollectionViewCell)
    //声明删除图片方法
    optional func removeButImage(cell:appendPhotosCollectionViewCell)
}

// MARK: -collviewcell的自定义
private class appendPhotosCollectionViewCell: UICollectionViewCell{
    
    //申明代理对象代理
    weak var appimageDelegate:appendPhotosCollectionViewCellDelegate?
    
    override init(frame:CGRect){
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 设置cell在面控件的ui
    func setupUI(){
        
        //添加控件
        contentView.addSubview(imageviewBut)
        contentView.addSubview(removeBut)
        
        //自动布局
        imageviewBut.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(contentView.snp_center)
            make.width.equalTo(contentView.snp_width)
            make.height.equalTo(contentView.snp_height)
        }
        
        removeBut.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        
    }
    /// 按钮监听的方法
    @objc private func removeButClick(){
        
        appimageDelegate?.removeButImage!(self)
        
    }
    //添加图片的按钮
    @objc private func addImage(){
        
        appimageDelegate?.appendPhotosCollectionViewCellfunc()
        
    }
    //点击含有图片的按钮的、进行更换图片
    @objc private func reoptionImage(){
        
        appimageDelegate?.imgeviewReoptionImage(self)
    }
    
    
    //设置按钮的图片
    var image: UIImage? {
        didSet{
            if image == nil {
                imageviewBut.setImage(UIImage(named: "compose_pic_add")!, forState: .Normal)
                imageviewBut.addTarget(self, action: "addImage", forControlEvents: UIControlEvents.TouchUpInside)
                removeBut.hidden = true
            }else{
                removeBut.hidden = false
                imageviewBut.removeTarget(self, action: "addImage", forControlEvents: UIControlEvents.TouchUpInside)
                imageviewBut.setImage(image, forState: .Normal)
                imageviewBut.addTarget(self, action: "reoptionImage", forControlEvents: UIControlEvents.TouchUpInside)
            }
            imageviewBut.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
            imageviewBut.imageView?.clipsToBounds = true
        }
    }
    
    /// 懒加载cell上面的控件
    private lazy var imageviewBut:UIButton = UIButton()
    
    private lazy var removeBut:UIButton = {
        
        let but = UIButton(imageName: "compose_photo_close")
        
        but.sizeToFit()
        
        but.addTarget(self, action: "removeButClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return but
        }()
}

// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate实现图片显示器的代理方法
extension appendPhotosVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    //没选择一张图片就会调用一次
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
       
        
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        let scaleImage = image.scaleToWith(600)
        
        var tempArray = [UIImage]()
        
        if selectionIndex >= arrayList.count  {
            
            tempArray.append(scaleImage)
            
            arrayList = tempArray + arrayList
        }else{
            arrayList[selectionIndex] = scaleImage
        }
        
        
        
        collectionView?.reloadData()
        
       picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

